

class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        // 1.先求出需要逆序多少组
        int n = 0;
        ListNode cur = head;
        while (cur != null) {
            cur = cur.next;
            n++;
        }
        n /= k;
        // 2.重复n次，长度为k的链表的逆序
        //创建一个虚拟的头结点
        ListNode newHead = new ListNode(0);
        ListNode prev = newHead;
        cur = head;
        for (int i = 0; i < n; i++) {
            ListNode tmp = cur;
            for (int j = 0; j < k; j++) {
                //头插的逻辑
                ListNode successor = cur.next;
                cur.next = prev.next;
                prev.next = cur;
                cur = successor;
            }
            prev = tmp;
        }
        //把后面不需要的进行连接
        prev.next = cur;
        return newHead.next;
    }
}

public class Test01 {

}
